package com.dotflat.survey.controller;

import com.dotflat.rest.controller.RestfulBaseController;
import com.dotflat.survey.domain.SurveyAnswer;
import com.dotflat.survey.domain.SurveyAnswerItem;
import com.dotflat.survey.domain.SurveySheet;
import com.dotflat.survey.domain.SurveySheetItem;
import com.dotflat.survey.dto.SurveyAnswerDTO;
import com.dotflat.survey.dto.SurveySheetDTO;
import com.dotflat.survey.po.SurveyAnswerItemPO;
import com.dotflat.survey.po.SurveyAnswerPO;
import com.dotflat.survey.po.SurveySheetPO;
import com.dotflat.survey.repository.SurveySheetItemRepository;
import com.dotflat.survey.service.SurveyAnswerItemService;
import com.dotflat.survey.service.SurveyAnswerService;
import com.starinside.wp.domain.Children;
import com.starinside.wp.domain.WxUser;
import com.starinside.wp.foundation.exception.BusinessException;
import com.starinside.wp.foundation.model.ErrorCode;
import com.starinside.wp.foundation.model.StatusResponse;
import com.starinside.wp.foundation.query.base.PagerQuery;
import com.starinside.wp.service.ChildrenService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

import java.util.ArrayList;
import java.util.List;

import static com.starinside.wp.foundation.constant.RequestConstant.TICKET;


@RestController
@RequestMapping("/v2/survey/answer")
@Slf4j
@Api(tags = "问卷 - 答题卡")
public class SurveyAnswerController extends RestfulBaseController<SurveyAnswer, SurveyAnswerService, SurveyAnswerPO> {

    @Autowired
    private ChildrenService childrenService;

    @Autowired
    private SurveyAnswerItemService answerItemService;

    @Autowired
    private SurveySheetItemRepository sheetItemRepository;

    @Autowired
    public void setBaseService(SurveyAnswerService service){
        super.setBaseService(service);
    }

    @Override
    @ApiOperation(value = "获取一个对象", response = SurveyAnswer.class)
    @GetMapping()
    public StatusResponse get(@RequestHeader(TICKET) String ticket, HttpServletRequest req, String id){
        return super.get(ticket, req, id);
    }

    @ApiOperation(value = "获取列表", response = SurveyAnswerDTO.class)
    @GetMapping("/list")
    public StatusResponse getList(@RequestHeader(TICKET) String ticket, HttpServletRequest req, SurveyAnswerPO param, PagerQuery pagerQuery){
        StatusResponse ret = super.getList(ticket, req, param, pagerQuery);

        Page<SurveyAnswer> page = (Page<SurveyAnswer>) ret.getData();

        Page<SurveyAnswerDTO> newPage = page.map(o-> SurveyAnswerDTO.of(o));

        return StatusResponse.success(newPage);
    }

    @ApiOperation(value = "增加一条记录", response = SurveyAnswer.class)
    @PostMapping()
    @Transactional(rollbackFor = RuntimeException.class)
    public StatusResponse add(@RequestHeader(TICKET) String ticket,  HttpServletRequest req,  SurveyAnswerPO param){

        WxUser loginUser = (WxUser) req.getSession().getAttribute("loginUser");

        if (loginUser.getDefaultBabyId() == null) {
            throw new BusinessException(ErrorCode.CHILDREN_NOT_EXIST, "当前家长没有就读的宝宝");
        }

        param.setParentId(loginUser.getParentId());
        param.setChildId(loginUser.getDefaultBabyId());

        if (param.getAnswers() == null || param.getAnswers().size() == 0){
            throw new BusinessException(ErrorCode.CHILDREN_NOT_EXIST, "答题卡不能为空");
        }

        Children children = childrenService.getById(param.getChildId());

        //创建答题卡
        SurveyAnswer ret = baseService.add(children.getAreaId(), "0", param);

        //创建答题卡条目
        List<SurveyAnswerItem> items = new ArrayList<>();

        for (SurveyAnswerItemPO answer : param.getAnswers()){

            SurveySheetItem sheetItem = sheetItemRepository.findFirstBySheetIdAndIdAndDeletedIsFalse(param.getSheetId(), answer.getItemId());
            if(sheetItem == null || ( sheetItem.getAreaId() != null && !sheetItem.getAreaId().equals(children.getAreaId()))){
                throw new BusinessException(ErrorCode.MATERIAL_NOT_EXIST, "选项不存在");
            }

            answer.setSeq(sheetItem.getSeq());
            answer.setItemTitle(sheetItem.getTitle());
            answer.setSheetId(sheetItem.getSheetId());
            answer.setAnswerId(ret.getId());

            SurveyAnswerItem  ans = answerItemService.add(children.getAreaId(), "0", answer);
            items.add(ans);
        }
        ret.setItems(items);

        return StatusResponse.success(ret);
    }
}
